<template>
  <div>
    <div class="search">
      <input type="text" placeholder="输入城市名称" class="search_input" v-model="keyword">
    </div>
    <div v-show="searchContentShow" ref="searchContent" class="search_content">
      <ul >
        <li class="search_content_item" v-for="item in searchList" :key="item.id" @click="handleCityClick(item.name)">
            {{item.name}}
        </li>
        <li class="search_content_item" v-if="searchList.length ==0">没有符合搜索条件的结果！</li>
      </ul>
    </div>
  </div>
</template>
<script>
import axios from 'axios'
import Bscroll from 'better-scroll'
export default {
  name: 'CitySearch',
  data () {
    return {
      keyword: '',
      searchContentShow: 0,
      searchList: [],
      timer: null
    }
  },
  methods: {
    handleCityClick (city) {
      this.$store.commit('changeCity', city)
      this.$router.push('/')
    }
  },
  watch: {
    keyword: function () {
      let cthis = this
      if (cthis.timer) {
        clearTimeout(this.timer)
      }
      cthis.timer = setTimeout(() => {
        if (this.keyword) {
          cthis.searchContentShow = 1
          axios.get('/api/city.json').then(function (res) {
            console.log(res)
            let tmpCities = []
            let ccities = res.data.data.cities
            for (var i in ccities) {
              for (var j = 0; j < ccities[i].length; j++) {
                if (ccities[i][j].name.indexOf(cthis.keyword) !== -1 || ccities[i][j].spell.indexOf(cthis.keyword) !== -1) {
                  tmpCities.push(ccities[i][j])
                }
              }
            }
            console.log(tmpCities)
            cthis.searchList = tmpCities
          })
        } else {
          cthis.searchContentShow = 0
        }
      }, 20)
    }
  },
  mounted () {
    this.scroll = new Bscroll(this.$refs.searchContent)
  }
}
</script>
<style scoped lang="stylus">
  @import '~styles/variables.styl'
.search
  height:.72rem;
  padding:0 .1rem;
  background:$bgColor
  .search_input
    height:.56rem;
    width:100%;
    border-radius:.04rem;
    display:block;
    text-align:center
.search_content
  position:absolute;
  left:0;
  right:0;
  top:1.58rem;
  bottom:0;
  z-index:3
  margin:auto;
  background:#f1f1f1
  overflow:hidden
  .search_content_item
    line-height:0.6rem;
    border-bottom:0.01rem solid #ccc;
    padding-left:.2rem;
    background:rgba(255,255,255,1);

</style>
